/* eslint-disable react/jsx-key */
import React, { useState } from 'react';
import s from './style.module.less';
import recursionForm from '@/common/recursionForm';
import TreeModel from './treeModel';
import {
    Dialog,
    Pagination,
    Button,
    Tooltip,
    Textarea,
    Input,
    Confirm,
    Loading,
    Form,
    Message,
    Icon,
    AntdTable
} from '@knownsec/react-component';
import { Table,ConfigProvider } from 'antd';
import gantan from '@/assets/svg/gantanhao.svg';
import i from '@/common.module.css'
import { BUG_GRADE } from '@/common/common';
import {
    customModuleList,
    customModuleQuery,
    customModuleUpdate,
    customModuleAdd,
    pluginList,
    customModuleDel,
} from '~/API';
import { uniqBy } from 'lodash-es';
import cn from 'classnames';

const keyforms = {
    name: '模版名称',
    plugin_list: '模版插件',
    description: '模版描述',
};
const CusLoading = (
    <Loading label="" />
)
const initForm = { name: '', description: '', plugin_list: [] };
export default function keyword() {
    const [refe, setRef] = useState(false);
    const [selectIds, setSelTable] = useState([]);
    const [loading, setLoading] = useState(true);
    const [initialValue, setInitValue] = useState(initForm);
    const [subtext, setText] = useState({});
    const [currentId, setCurrentId] = useState('');
    const [visible, setVisible] = useState(0); //1、新增 2、编辑
    const [visibleD, setVisibleD] = useState(''); //查看详情
    const [total, setTotal] = useState(0);
    const [page, setPage] = useState({ page: 1, limit: 10 });
    const [tableData, setTableData] = useState([]);
    const [pluginListData, setPluginList] = useState([]);
    const [isFull, setIsFull] = useState(0);
    const createForm = React.useRef();
    const columns = [
        {
            title: '模版名称',
            dataIndex: 'name',
            render: (e, row) => {
                return (
                    <span>
                        {row.display_name?.zh_cn ? row.display_name.zh_cn : row.description}
                    </span>
                );
            },
        },
        {
            title: '含插件数',
            dataIndex: 'plugins_count',
            render:(e)=>{return e||0}
        },
        {
            //#f3bb86
            title: '严重',
            dataIndex: 'plugin_severity',
            render: (e) => {
                return <span>{e[5] || 0}</span>;
            },
        },
        {
            //#7cafd4
            title: '高危',
            dataIndex: 'plugin_severity',
            render: (e) => {
                return <span>{e[4] || 0}</span>;
            },
        },
        {
            //#82cddb
            title: '中危',
            dataIndex: 'plugin_severity',
            render: (e) => {
                return <span>{e[3] || 0}</span>;
            },
        },
        {
            //#82cddb
            title: '低危',
            dataIndex: 'plugin_severity',
            render: (e) => {
                return <span>{e[2] || 0}</span>;
            },
        },
        {
            //#82cddb
            title: '信息',
            dataIndex: 'plugin_severity',
            render: (e) => {
                return <span>{e[1] || 0}</span>;
            },
        },
        {
            title: '描述',
            dataIndex: 'description',
            render: (e) => {
                return e ? (
                    <Tooltip className={s.ml100} overlay={<p>{e}</p>} placement={'top'}>
                        <span className={s.w_span}>{e}</span>
                    </Tooltip>
                ) : (
                    '--'
                );
            },
        },
        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            className: s.option,
            render: (e, row) => {
                return (
                    <>
                        {row.id && (
                            <span
                                className={s.operation}
                                onClick={() => {
                                    editModule(row);
                                }}
                            >
                                修改
                            </span>
                        )}
                        <span
                            className={s.operation}
                            onClick={() => {
                                showDetails(row);
                            }}
                        >
                            查看
                        </span>
                        {row.id && (
                            <span
                                className={s.operation}
                                onClick={() => {
                                    delModule([row.id]);
                                }}
                            >
                                删除
                            </span>
                        )}
                    </>
                );
            },
        },
    ];
    const getList = async (e) => {
        const e_ = e ? e : page;
        setTableData([]);
        setLoading(true);
        const list = await customModuleList(e_);
        if(!list.data.templates[0]&&page.page>1){
            setPage({ limit: 10, page: page.page-1 })
            getList({ limit: 10, page: page.page-1 })
            return false;
        }
        list.data.templates.map((item) => {
            item.id = item.custom_profile_template_id;
            item.key = item.custom_profile_template_id;
        });
        setTotal(list.data.total);
        if (list.data.total - list.data.sys_template_count >= list.data.max_count) {
            setIsFull(list.data.max_count);
        } else {
            setIsFull(0);
        }
        setTableData(list.data.templates);
        setLoading(false);
        setText({});
    };
    function onSearchChange(data) {
        setPage(data);
        getList(data);
    }
    const getPluginList = async (key = '') => {
        setLoading(true);
        const list = await pluginList({ search_key: key });
        const data = list?.data?.plugin_list || [];
        let pl = uniqBy(data, 'key');
        pl = pl.map((item) => {
            const i = {
                cn_name: item.name.zh_cn || '-',
                en_name: item.name.en_us || '-',
                key_name: item.key,
                category_cn: item.vuln_type[0].zh_cn,
                category_en: item.vuln_type[0].en_us,
            };
            return i;
        });
        getList();
        setPluginList(pl);
    };

    function delModule(e) {
        Confirm({
            title: '提示',
            pro: true,
            message: <div className="confirmbox">确认要删除选中的模版吗？</div>,
            onconfirm: () => {
                const ids = e ? e : selectIds;
                const params = { template_ids: ids };
                customModuleDel(params).then((res) => {
                    if (res.status == 'success') {
                        setSelTable([]);
                        setRef(!refe);
                        getList();
                        // getsum();
                        Message.show({
                            pro: true,
                            type: 'success',
                            message: '删除模版成功',
                            showClose: false,
                        });
                    }
                });
            },
            oncancel: () => {},
        });
    }
    const onValues = (data, val) => {
        let values = recursionForm(data);
        createForm.current.setFieldsValue(values);
        setText(val);
    };
    const editModule = async (row) => {
        const id = row.custom_profile_template_id;
        setCurrentId(id);
        const keylist = await customModuleQuery(id);
        setInitValue(keylist.data);
        createForm.current.setFieldsValue(keylist.data);
        const d = Object.assign({ name: { value: keylist.data.name || '' } }, keylist.data);
        setText(d);
        setVisible(2);
    };
    const showDetails = async (row) => {
        setVisibleD(row);
    };
    const addModule = async () => {
        createForm.current.setFieldsValue(initForm);
        setVisible(1);
        setCurrentId('');
        setInitValue(initForm);
    };
    const submitForm = async () => {
        // try {
        //      await createForm.current.validateFields(['name','plugin_list']);
        //   } catch (errorInfo) {
        //       return false;
        //   }
        const data = {
            description: subtext.description,
            plugin_list: subtext.plugin_list,
            name: typeof subtext.name === 'string' ? subtext.name : subtext.name.value,
        };
        if (visible == 2) {
            customModuleUpdate({ data: data, id: currentId })
                .then((res) => {
                    if (res.status === 'success') {
                        Message.show({
                            pro: true,
                            type: 'success',
                            message: '操作成功',
                            showClose: false,
                        });
                        getList();
                        setVisible(0);
                    } else {
                        Message.show({
                            pro: true,
                            type: 'error',
                            message: '操作失败',
                            showClose: false,
                        });
                    }
                })
                .catch((err) => {
                    errdetail(err);
                });
        } else if (visible == 1) {
            customModuleAdd(data)
                .then((res) => {
                    if (res.status === 'success') {
                        Message.show({
                            pro: true,
                            type: 'success',
                            message: '操作成功',
                            showClose: false,
                        });
                        getList();
                        setVisible(0);
                    } else {
                        Message.show({
                            pro: true,
                            type: 'error',
                            message: '操作失败',
                            showClose: false,
                        });
                    }
                })
                .catch((err) => {
                    errdetail(err);
                });
        }
    };
    const errdetail = (err) => {
        const errmsg =
            keyforms[Object.keys(err.data)[0]] + ': ' + Object.values(err.data)[0] || '操作失败';
        const errmsg_ = errmsg.replace('undefined:', '');
        Message.show({
            pro: true,
            type: 'error',
            message: errmsg_,
            showClose: false,
        });
    };
    const rowSelection = {
        selectedRowKeys: selectIds,
        onChange: (selectedRowKeys) => {
            setSelTable(selectedRowKeys);
        },
        getCheckboxProps: (record) => ({
            disabled: record.id === '',
        }),
    };
    const CustomSIze=()=>{
        return	 (
            <div className={cn(i.p30, i.w100p, i.blackLineColor, i.fs14, i.tac)}>
                暂无数据
            </div>
        )
    }
    React.useMemo(() => {
        getPluginList();
    }, []);
    return (
        <div className={s.wordMain}>
            <p className={s.wordMain_h} style={{ display: isFull ? 'block' : 'none' }}>
                <img src={gantan} alt="" /> 系统最多可添加{isFull}条漏洞检测模版
                {/* <Icon type="cancel" className={cn(s.closeDialogBtn)} onClick={() =>{ setVisibleD('')}}/> */}
            </p>
            {/* <Loading show={loading} label="" /> */}
            <div className={s.tool}>
                <div className={s.searchLeft}>
                    <Button
                        className={s.mr20}
                        pro
                        type="primary"
                        onClick={() => addModule()}
                        disabled={isFull}
                    >
                        添加
                    </Button>
                </div>
            </div>
            <div>
                <Button
                    disabled={!selectIds.length}
                    onClick={() => {
                        delModule();
                    }}
                    className={cn(s.mr20, 'delete-btn', 'p0')}
                    pro
                    type="text"
                >
                    删除
                </Button>
            </div>
            <ConfigProvider renderEmpty={CustomSIze}>
                <AntdTable
                    rowSelection={{
                        ...rowSelection,
                    }}
                    loading={loading ? {indicator: CusLoading} : false}
                    columns={columns}
                    dataSource={tableData}
                    className={s.table}
                    pagination={false}
                />
            </ConfigProvider>
            {total > 10 && <Pagination
                key={Number(123)}
                className={s.pagination}
                current={page.page}
                showQuickJumper={{ goButton: true }}
                showSizeChanger={true}
                pageSize={page.limit}
                pageSizeOptions={['10', '20', '50']}
                total={total}
                showTotal={(total) => `共${total}条`}
                onChange={(page, size) => {
                    onSearchChange({ page, limit: size });
                }}
            />}
            {/* 新增/修改 */}
            <Dialog
                // className={s.moduleDialog}
                className={cn(s.w640, s.t10vh)}
                title={visible == 1
                    ? '添加漏洞模版'
                    : visible == 2
                    ? '修改漏洞模版'
                    : '漏洞模版'}
                maskClosable={true}
                cancelText="取消"
                confirmText="确定"
                onsubmit={() => submitForm()}
                onhide={() => {
                    setVisible(0);
                    setInitValue(initForm);
                }}
                visible={visible}
            >
                <div className={s.p24}>
                    <Form
                        ref={createForm}
                        className="form"
                        labelAlign='right'
                        labelCol={{span: 3}}
                        initialValues={initialValue}
                        onValuesChange={(newItem, allvalue) => {
                            onValues(newItem, allvalue);
                        }}
                    >
                        <Form.Item
                            label="模版名称"
                            name="name"
                            required
                            initialValue={initialValue.name}
                            // rules={[{ required: true, message: '请输入模版名称' }]}
                        >
                            <Input
                                pro
                                className={s.inputstyle}
                                placeholder="请输入模版名称，不超过32个字符"
                                type="text"
                                autoComplete={'off'}
                                maxlength={32}
                            />
                        </Form.Item>
                        <Form.Item
                            name="plugin_list"
                            label="模版插件"
                            required
                            initialValue={initialValue.plugin_list}
                            resetFields
                        >
                            {visible && pluginListData[0] && (
                                <TreeModel
                                    list={pluginListData}
                                    init={initialValue.plugin_list}
                                    visible={visible}
                                ></TreeModel>
                            )}
                        </Form.Item>
                        <Form.Item
                            label="模版描述"
                            name="description"
                            initialValue={initialValue.description}
                        >
                            <Textarea
                                className={s.textArea}
                                placeholder="请输入描述，不超过100个字符"
                                maxlength={100}
                            ></Textarea>
                        </Form.Item>
                    </Form>
                </div>
            </Dialog>
            {/* 查看 */}
            <Dialog
                className={cn(s.moduleDialog2, s.w840)}
                title='查看详情'
                maskClosable={true}
                cancelText=""
                confirmText="关闭"
                onsubmit={() => setVisibleD('')}
                onhide={() => {
                    setVisibleD('');
                }}
                visible={visibleD}
            >
                <div className={cn(s.p24)}>
                    <table className={s.diaTab}>
                        <tr>
                            <td className={s.keyTd}>模版名称</td>
                            <td>
                                {visibleD.display_name?.zh_cn
                                    ? visibleD.display_name.zh_cn
                                    : visibleD.description}
                            </td>
                        </tr>
                        <tr>
                            <td className={s.keyTd}>含插件数</td>
                            <td>{visibleD?.plugins_count}</td>
                        </tr>{' '}
                        <tr>
                            <td className={s.keyTd}>插件详情</td>
                            <td className={s.keyDet}>
                                <div className={s.detailTD}>
                                    {visibleD &&
                                        Object.entries(visibleD?.plugin_types).map(([key, val]) => {
                                            return (
                                                <>
                                                    <p className={s.detailP}>
                                                        <span>{key} </span>
                                                    </p>
                                                    <div className={s.detailD}>
                                                        {val.map((e,i) => {
                                                            return <span className={s.detailSpan} title={s.detail}>{e}</span>;
                                                        })}
                                                        {val.length%2!==0&& <span className={s.detailSpan} title={s.detail}></span>}
                                                    </div>
                                                    <p style={{ height: '2rem' }}></p>
                                                </>
                                            );
                                        })}
                                </div>
                            </td>
                        </tr>
                    </table>
                </div>
            </Dialog>
        </div>
    );
}
